﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;


namespace ConceptLink
{
    public class Search : JSPTask
    {
        public class SearchResult : Article
        {
            public float commoness { get; set; }
        }

        private class _Store
        {
            public string a;
            public string b;
            public float c;
            public string t;
            public int i;

            internal SearchResult ToSearchResult()
            {
                return new SearchResult() { title = b, commoness = c, description = t, id = i };
            }
        }

        private static List<_Store> cache = new List<_Store>();


        public static SearchResult Get(int id)
        {

            lock (cache)
            {
                foreach (var entry in cache)
                    if (entry.i == id)
                        return entry.ToSearchResult();

            }
            return null;

        }
        
        public delegate void SearchResultsCallback(string search, SearchResult[] results);

        public static void Get(int id, SearchResultsCallback callback)
        {

            List<SearchResult> results = new List<SearchResult>();


            lock (cache)
            {
                foreach (var entry in cache)
                    if (entry.i == id)
                    {
                        var res = entry.ToSearchResult();
                        results.Add(res);
                        callback("id search!", results.ToArray());
                        return;
                    }
            }



            GetXml(
                string.Format(linkurl, id),
                delegate(XDocument x)
                {
                    if (x == null)
                    {
                        callback(null, null);
                        return;
                    }


                    var node = x.Descendants("Article").FirstOrDefault();

                    if (node != null)
                    {
                        _Store entry = new _Store()
                        {
                            a = "id search!",
                            b = node.Attribute("title").Value,
                            c = 1,
                            i = int.Parse(node.Attribute("id").Value),
                            t = node.Descendants("FirstParagraph").First().Value
                        };

                        lock (cache)
                        {
                            cache.Add(entry);
                        }

                        callback("id search!", new SearchResult[] { entry.ToSearchResult() });
                    }
                    else
                    {
                        callback("id search!", null);
                    }

                }
                );



        }

        public static void Get(string article1, SearchResultsCallback callback)
        {
            string articlea = article1.ToLower();

            List<SearchResult> results = new List<SearchResult>();

            if (article1.Length < 2)
            {
                callback(article1, results.ToArray());
                return;
            }

            lock (cache)
            {
                foreach (var entry in cache)
                    if (entry.a == articlea)
                    {
                        results.Add(entry.ToSearchResult());
                    }
            }

            if (results.Count != 0)
            {
                callback(article1, results.ToArray());
            }
            else
            {

                GetXml(
                    string.Format(searchurl, Uri.EscapeDataString(articlea)),
                    delegate(XDocument x)
                    {
                        if (x == null)
                        {
                            callback(article1, null);
                            return;
                        }

                        var found = (
                            from element in x.Descendants("Sense")
                            select new _Store() {
                                a = articlea,
                                b = element.Attribute("title").Value,
                                c = element.Attribute("commonness") != null ? float.Parse(element.Attribute("commonness").Value) : -1,
                                i = int.Parse(element.Attribute("id").Value),
                                t = DeHTMLize(element.Descendants("FirstSentence").FirstOrDefault())
                            }
                            ).ToArray();


                        if (found.Length != 0)
                        {
                            lock (cache)
                            {
                                cache.AddRange(found);
                            }

                            var ret = from e in found select e.ToSearchResult();

                            callback(article1, ret.ToArray());
                        }
                        else
                        {
                            var node = x.Descendants("Article").FirstOrDefault();

                            if (node != null)
                            {
                                _Store entry = new _Store()
                                {
                                    a = articlea,
                                    b = node.Attribute("title").Value,
                                    c = 1,
                                    i = int.Parse(node.Attribute("id").Value),
                                    t = node.Descendants("FirstParagraph").First().Value
                                };

                                lock (cache)
                                {
                                    cache.Add(entry);
                                }
                                    
                                callback(article1, new SearchResult[] { entry.ToSearchResult() });
                            }
                            else
                            {
                                callback(article1, null);
                            }
                        }
                    }
                    );

            }

        }

        private static string DeHTMLize(XElement xElement)
        {
            string s = "";

            if (xElement == null)
                return s;
            
            foreach (var e in xElement.DescendantNodes())
            {
                if (e is XText)
                {
                    string a = (e as XText).Value;

                    if (a.Length > 0)
                    {
                        if (s.Length > 0)                        
                            if (char.IsLetterOrDigit(s[s.Length - 1]) &&
                                char.IsLetterOrDigit(a[0]))
                                s += " ";
                        
                        s += a;
                    }
                }
            }

            return s.Replace("  ", " ");
        }

    }
}

